package com.ljh.myaiagent.advisor;

import com.ljh.myaiagent.config.ForbiddenWordConfig;
import com.ljh.myaiagent.service.PromptTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.*;

@Slf4j
@Component
public class ForbiddenWordAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    private final ForbiddenWordConfig forbiddenWordConfig;
    private final PromptTemplateService promptTemplateService;
    
    public ForbiddenWordAdvisor(ForbiddenWordConfig forbiddenWordConfig, PromptTemplateService promptTemplateService) {
        this.forbiddenWordConfig = forbiddenWordConfig;
        this.promptTemplateService = promptTemplateService;
    }



    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        // 如果违禁词检测未启用，直接跳过
        if (!forbiddenWordConfig.isEnabled()) {
            return chain.nextAroundCall(advisedRequest);
        }
        String userText = advisedRequest.userText();
        if(containsForbiddenWord(userText)){
            log.warn("请求包含敏感词: {}", userText);
            // 返回违禁词提示响应，阻止继续处理
            return createForbiddenResponse(advisedRequest);
        }
        return chain.nextAroundCall(advisedRequest);
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        // 如果违禁词检测未启用，直接跳过
        if (!forbiddenWordConfig.isEnabled()) {
            return chain.nextAroundStream(advisedRequest);
        }
        // 检查用户输入是否包含违禁词
        String userText = advisedRequest.userText();
        if (containsForbiddenWord(userText)) {
            log.warn("流式请求包含敏感词: {}", userText);
            // 对于流式请求，我们返回一个包含违禁词提示的单次响应
            AdvisedResponse forbiddenResponse = createForbiddenResponse(advisedRequest);
            return Flux.just(forbiddenResponse);
        }
        // 如果没有违禁词，继续正常处理
        return chain.nextAroundStream(advisedRequest);
    }

    private AdvisedResponse createForbiddenResponse(AdvisedRequest advisedRequest) {
        String userText = advisedRequest.userText();
        String forbiddenWords = findForbiddenWords(userText);

        // 使用Prompt模板服务生成响应
        String responseText = promptTemplateService.generateForbiddenWordPrompt(userText, forbiddenWords);
        
        // 由于Spring AI接口复杂，我们直接抛出一个异常来阻止处理
        // 这样可以在上层捕获并处理违禁词情况
        throw new RuntimeException("检测到违禁词: " + responseText);
    }

    private boolean containsForbiddenWord(String userText) {
        if(userText == null || userText.isEmpty()){
            return false;
        }
        String lowerText = userText.toLowerCase();
        for (String forbiddenWord : forbiddenWordConfig.getWords()) {
            if(lowerText.contains(forbiddenWord.toLowerCase())){
                return true;
            }
        }
        return false;
    }

    /**
     * 查找文本中包含的违禁词
     */
    private String findForbiddenWords(String userText) {
        if(userText == null || userText.isEmpty()){
            return "";
        }

        Set<String> foundWords = new HashSet<>();
        String lowerText = userText.toLowerCase();

        for (String forbiddenWord : forbiddenWordConfig.getWords()) {
            if(lowerText.contains(forbiddenWord.toLowerCase())){
                foundWords.add(forbiddenWord);
            }
        }

        return String.join(", ", foundWords);
    }

    @Override
    public String getName()  {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
